//
//  AppleScriptCommand.swift
//  JKTools
//
//  Created by 姜奎 on 2021/4/22.
//

import Foundation
import Cocoa

extension String {
    func fourCharCode() -> FourCharCode
    {
        return self.utf16.reduce(0, {$0 << 8 + FourCharCode($1)})
    }
}

enum ToolName: String {
    case Terminal = "Terminal"
    case Xcode = "Xcode"
}

class AppleScriptCommand {
    let toolName: ToolName
    let script: String
    let path: String
    init(toolName: ToolName, script: String, path:String = "") {
        self.toolName = toolName
        self.script = script
        self.path = path
    }

    func run(completion: @escaping (String?) -> Void) {

        let parameters = NSAppleEventDescriptor.list()
        parameters.insert(NSAppleEventDescriptor(string: toolName.rawValue), at: 0)
        parameters.insert(NSAppleEventDescriptor(string: script), at: 0)
        parameters.insert(NSAppleEventDescriptor(string: path), at: 0)

        let event = NSAppleEventDescriptor(
            eventClass: AEEventClass("ascr".fourCharCode()),
            eventID: AEEventID("psbr".fourCharCode()),
            targetDescriptor: nil,
            returnID: AEReturnID(kAutoGenerateReturnID),
            transactionID: AETransactionID(kAnyTransactionID)
        )
        event.setDescriptor(NSAppleEventDescriptor(string: "JKToolScript"), forKeyword: AEKeyword("snam".fourCharCode()))
        event.setDescriptor(parameters, forKeyword: AEKeyword(keyDirectObject))

        let applicationScriptsDirectory = try? FileManager.default.url(for: .applicationScriptsDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

        let scptPath = applicationScriptsDirectory?.appendingPathComponent("JKToolScript")
            .appendingPathExtension("scpt")

        guard let scptPath = scptPath else {
            return
        }

        guard let _ = Bundle.appleScript(forResource: "JKToolScript", withExtension: "scpt") else {
            return completion("安装包中不存在自动更新程序")
        }


        if FileManager.default.fileExists(atPath: scptPath.path) == false {
            Alert.alert(message: "请重新安装JKToolScript", buttons: ["立即安装","取消"]) { resp in
                switch resp {
                    case .alertFirstButtonReturn:
                        Self.installJKToolAppleScript { error in
                            if let error = error {
                                return completion(error)
                            }

                            do {
                                let appleScript = try NSUserAppleScriptTask(url: scptPath)
                                appleScript.execute(withAppleEvent: event) { result, error in
                                    if let error = error {
                                        completion("\(error)")
                                    } else {
                                        completion(nil)
                                    }
                                }
                            } catch {
                                completion("\(error)")
                            }
                        }
                    default:
                        break
                }
            }
            return
        }

        do {
            let appleScript = try NSUserAppleScriptTask(url: scptPath)
            appleScript.execute(withAppleEvent: event) { result, error in
                if let error = error {
                    completion("\(error)")
                } else {
                    completion(nil)
                }
            }
        } catch {
            completion("\(error)")
        }
    }

    static func installJKToolAppleScript(completion: @escaping (String?) -> Void) {
        guard let applicationScriptsDirectory = try? FileManager.default.url(for: .applicationScriptsDirectory, in: .userDomainMask, appropriateFor: nil, create: true),
              let scriptUrl = Bundle.appleScript(forResource: "JKToolScript", withExtension: "scpt") else {
            return completion("安装包中不存在自动更新程序")
        }
        let scptPath = applicationScriptsDirectory.appendingPathComponent("JKToolScript")
            .appendingPathExtension("scpt")


        NSOpenPanel.open(directoryURL: applicationScriptsDirectory) { _ in
            do {
                try? FileManager.default.removeItem(at: scptPath)
                try FileManager.default.copyItem(at: scriptUrl, to: scptPath)
                completion(nil)
            } catch {
                completion("\(error)")
            }
        }
    }
}
